﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LambdaToSql.FrameWork
{
    /// <summary>
    /// 缓存帮助类
    /// </summary>
    internal class CacheHelper
    {
        #region 私有属性

        /// <summary>
        /// 字典
        /// </summary>
        static Dictionary<string, object> dic = new Dictionary<string, object>();

        /// <summary>
        /// 定义一个静态变量来保存类的实例
        /// </summary>
        static CacheHelper session;

        /// <summary>
        /// 定义一个标识确保线程同步
        /// </summary>
        static readonly object locker = new object(); 
        #endregion

        #region Instance 单例

        /// <summary>
        /// 单例
        /// </summary>
        /// <returns>返回类型为Session</returns>
        public static CacheHelper Instance
        {
            get
            {
                if (session == null)
                {
                    lock (locker)
                    {
                        if (session == null)// 如果类的实例不存在则创建，否则直接返回
                        {
                            session = new CacheHelper();
                        }
                    }
                }
                return session;
            }
        } 
        #endregion

        #region Remove 移除

        /// <summary>
        /// 删除成员
        /// </summary>
        /// <param name="name"></param>
        public void Remove(string name)
        {
            dic.Remove(name);
        }

        /// <summary>
        /// 删除全部成员
        /// </summary>
        public void RemoveAll()
        {
            dic.Clear();
        } 
        #endregion

        #region 本类的索引器

        /// <summary>
        /// 本类的索引器
        /// </summary>
        /// <returns>返回Object成员</returns>
        public Object this[string index]
        {
            get
            {
                if (dic.ContainsKey(index))
                {
                    Object obj = (Object)dic[index];
                    return obj;
                }
                return null;
            }
            set
            {
                if (dic.ContainsKey(index))
                {
                    dic.Remove(index);
                }
                dic.Add(index, value);
            }
        } 
        #endregion
    }
}
